import asyncio
import os


from tidy_core.file_tool import copy_file


async def mapping(mapping_dir_path, source_dir_path_lst, is_require_dir):
        copy_tasks = []

        if is_require_dir:
            def path_generator(dir_name):
                return os.path.join(mapping_dir_path, dir_name)

        else:
            def path_generator(dir_name=None):
                return mapping_dir_path

        def walk_copy_file(file_or_dir_path):
            if os.path.isdir(file_or_dir_path):
                for sub_file_or_dir_path in os.listdir(file_or_dir_path):
                    walk_copy_file(sub_file_or_dir_path)

            else:
                dir_name, file_name = os.path.split(file_or_dir_path)
                abs_dist_dir_path = os.path.abspath(path_generator(dir_name))

                if not os.path.exists(abs_dist_dir_path):
                    os.mkdir(abs_dist_dir_path)


                abs_dist_file_path = os.path.join(abs_dist_dir_path,file_name)
                copy_tasks.append(asyncio.create_task(copy_file(abs_dist_file_path, file_or_dir_path)))

        for source_dir_path in source_dir_path_lst:
            for file_or_dir_path in os.listdir(source_dir_path):
                walk_copy_file(file_or_dir_path)
        await asyncio.wait(copy_tasks)